// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package dao

import (
	"context"
	"time"

	"gitcode.com/lvupclub/lvup-api/config"
	"gitcode.com/lvupclub/lvup-api/dao/resource_dao"
	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/lvup-api/notice_serv"
	"github.com/redis/go-redis/v9"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

var _mongoClient *mongo.Client

var CacheDao *_CacheDao

func connMongoDb(dbUrl, dbName string) (*mongo.Database, error) {
	clientOpts := options.Client().ApplyURI(dbUrl).SetConnectTimeout(10 * time.Second)
	client, err := mongo.Connect(clientOpts)
	if err != nil {
		return nil, err
	}
	return client.Database(dbName), nil
}

func InitDao(servCfg *config.ServerConfig) (err error) {
	mongoDb, err := connMongoDb(servCfg.DataBase.Mongo.Url, servCfg.DataBase.Mongo.DataBase)
	if err != nil {
		return err
	}
	rdb := redis.NewClient(&redis.Options{
		Addr:     servCfg.DataBase.Redis.Addr,
		Password: servCfg.DataBase.Redis.PassWord,
	})
	_mongoClient = mongoDb.Client()

	err = notice_serv.Init(rdb)
	if err != nil {
		return err
	}

	CacheDao, err = newCacheDao(rdb)
	if err != nil {
		return
	}
	err = user_dao.InitDao(mongoDb)
	if err != nil {
		return
	}
	err = roadmap_dao.InitDao(mongoDb)
	if err != nil {
		return
	}
	err = resource_dao.InitDao(mongoDb)
	if err != nil {
		return
	}
	return
}

func StartSession() (*mongo.Session, error) {
	return _mongoClient.StartSession()
}

func EndSession(sess *mongo.Session) {
	sess.EndSession(context.Background())
}
